import argparse
import asyncio
import os
from datetime import datetime
from typing import List
from threading import Thread

import jsonpickle
from flask import Flask
from flask_migrate import Migrate
from gevent import pywsgi
import time

from timelog_backend.controller.tag_controller import tag_bp
from timelog_backend.databus import db
from timelog_backend.env import *
from timelog_backend.databus import daemon_thread_pool, thread_pool
from threading import Thread
from timelog_backend.task import timelog_task
from flask_executor import Executor
from flask_apscheduler import APScheduler
from timelog_backend.service.os.instance import device
from timelog_backend.service.tag_service import TagService
from timelog_backend.config import FlaskConfig, MyConfig
import os

parser = argparse.ArgumentParser(description='Timelog')
parser.add_argument('--debug', action='store_true',
                    help='flask是否开启debug模式，当该模式开启时会热加载，但是不能用于断点调试')
parser.add_argument('--prod', action='store_true', help='flask是否开启生产模式')
parser.add_argument('-p', '--port', default='9090', help='端口')
parser.add_argument('--host', default='127.0.0.1', help='端口')
args, _ = parser.parse_known_args()
port = args.port
host = args.host

app = Flask(__name__)
app.config.from_object(FlaskConfig)
db.init_app(app)
migrate = Migrate(app, db)
executor = Executor(app)
scheduler = APScheduler()
scheduler.init_app(app)

app.register_blueprint(tag_bp)

@app.route('/', methods=['GET', 'POST'])
def index():
    timelog_task()
    return "ok"

@app.cli.command()
def setup():
    print('setup')

@scheduler.task('interval', id='record_timer', seconds=MyConfig.timelog_interval)
def timelog():
    with app.app_context():
        timelog_task()

scheduler.start()

if __name__ == '__main__':

    # with app.app_context():
    #     # 在请求上下文中执行需要请求上下文的代码
    #     with app.test_request_context():
    #         # 在测试请求上下文中执行需要请求上下文的代码
    #         t = Thread(target= record_timer, args=(app, 5), daemon=True)
    #         executor.submit(t)

    if args.prod:
        # 生产环境
        server = pywsgi.WSGIServer((host, port), app)
        server.serve_forever()
    else:
        app.run(host=host, port=port, debug=args.debug)
    
